import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';
import 'package:yyshort/common/apis/apis.dart';

class FeedbackPage extends StatefulWidget {
  const FeedbackPage({super.key});

  @override
  State<FeedbackPage> createState() => _FeedbackPageState();
}

class _FeedbackPageState extends State<FeedbackPage> {
  // 文本编辑控制器
  final TextEditingController _feedbackController = TextEditingController();
  // 最大输入字数限制
  final int _maxLength = 200;
  // 当前输入字数
  int _currentLength = 0;
  // 控制加载指示器显示状态
  bool _isLoading = false;
  // 防止重复提交的锁
  bool _isSubmitting = false;
  // 防止重复显示空内容提示的锁
  bool _isShowingEmptyHint = false;

  // 反馈用户联系方式控制器
  final TextEditingController _contactController = TextEditingController();
  // 联系方式输入字符限制
  final int _contactMaxLength = 100;
  // 联系方式当前字符数
  int _contactCurrentLength = 0;

  @override
  void initState() {
    super.initState();
    _currentLength = _feedbackController.text.length;
    _feedbackController.addListener(_updateCharacterCount);

    _contactCurrentLength = _contactController.text.length;
    _contactController.addListener(_updateContactCharacterCount);
  }

  void _updateCharacterCount() {
    setState(() {
      _currentLength = _feedbackController.text.length;
    });
  }

  void _updateContactCharacterCount() {
    setState(() {
      _contactCurrentLength = _contactController.text.length;
    });
  }

  // 提交反馈
  Future<void> _submitFeedback() async {
    // 如果正在提交中或正在显示空提示，直接返回
    if (_isSubmitting || _isShowingEmptyHint) return;

    FocusManager.instance.primaryFocus?.unfocus();
    String feedback = _feedbackController.text.trim();
    // 联系方式
    String contact = _contactController.text.trim();

    if (feedback.isEmpty || contact.isEmpty) {
      // 标记为正在显示空提示
      setState(() {
        _isShowingEmptyHint = true;
      });

      if (contact.isEmpty) {
        // 联系方式为空提示
        _showSnackBar('请输入您的联系方式'.tr, isError: true);
      } else if (feedback.isEmpty) {
        // 反馈内容为空提示
        _showSnackBar('请输入您的反馈内容'.tr, isError: true);
      }

      // 延迟一段时间后重置空提示状态，避免频繁提示
      Future.delayed(const Duration(seconds: 2), () {
        if (mounted) {
          setState(() {
            _isShowingEmptyHint = false;
          });
        }
      });
      return;
    }

    // 标记为正在提交
    setState(() {
      _isSubmitting = true;
      _isLoading = true;
    });

    try {
      _feedbackController.clear();
      _contactController.clear();
      bool temp = await UserAPI.add_user_feedback(
        content: feedback,
        contact: contact,
      );

      if (temp) {
        _showSnackBar('反馈提交成功，感谢您的宝贵意见！'.tr);
      } else {
        _showSnackBar('反馈提交失败，请稍后重试'.tr, isError: true);
      }
    } catch (e) {
      _showSnackBar('提交过程出错：${e.toString()}'.tr, isError: true);
    } finally {
      // 重置提交状态
      setState(() {
        _isSubmitting = false;
        _isLoading = false;
      });
    }
  }

  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  void dispose() {
    _feedbackController.removeListener(_updateCharacterCount);
    _feedbackController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => KeyboardDismisser(
    gestures: [GestureType.onTap, GestureType.onPanUpdateDownDirection],
    child: Scaffold(
      backgroundColor: Colors.grey[900],
      appBar: AppBar(
        title: Text('用户反馈'.tr, style: const TextStyle(color: Colors.white)),
        centerTitle: true,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Text(
                  '请输入您的联系方式：'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 12),
                // 邮箱输入框
                TextFormField(
                  controller: _contactController,
                  // 限制输入类型为邮箱格式（会调出带@的键盘）
                  keyboardType: TextInputType.emailAddress,
                  // 输入文本样式
                  style: const TextStyle(color: Colors.white, fontSize: 16),
                  maxLength: _contactMaxLength,
                  maxLengthEnforcement: MaxLengthEnforcement.enforced,
                  // 输入框装饰
                  decoration: InputDecoration(
                    // 提示文本
                    hintText: '请输入邮箱地址'.tr,
                    hintStyle: const TextStyle(color: Colors.grey),
                    // 输入框边框样式
                    border: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.grey),
                    ),
                    // 聚焦时边框样式
                    focusedBorder: const OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.blue),
                    ),
                    // 内容内边距
                    contentPadding: const EdgeInsets.all(12),
                    // 填充颜色
                    filled: true,
                    fillColor: Colors.grey[800],
                    // 计数器文本
                    counter: Text(
                      '$_contactCurrentLength/$_contactMaxLength',
                      style: TextStyle(
                        fontSize: 12,
                        color: _contactCurrentLength >= _contactMaxLength
                            ? Colors.red
                            : Colors.white70,
                      ),
                    ),
                    counterText: '',
                    // 错误提示样式（校验不通过时显示）
                    errorStyle: const TextStyle(
                      color: Color(0xFFFF4D4F), // 错误提示颜色
                      fontSize: 12,
                    ),
                  ),
                  autofocus: true,
                  // 提交过程中禁用输入
                  enabled: !_isSubmitting,
                ),
                const SizedBox(height: 12),
                Text(
                  '请输入您的反馈或建议：'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                    color: Colors.white,
                  ),
                ),
                const SizedBox(height: 12),

                ConstrainedBox(
                  constraints: const BoxConstraints(maxHeight: 200),
                  child: TextField(
                    controller: _feedbackController,
                    maxLines: null,
                    keyboardType: TextInputType.multiline,
                    maxLength: _maxLength,
                    maxLengthEnforcement: MaxLengthEnforcement.enforced,
                    style: const TextStyle(color: Colors.white, fontSize: 16),
                    decoration: InputDecoration(
                      hintText: '请详细描述您遇到的问题或提出的建议...'.tr,
                      hintStyle: const TextStyle(color: Colors.grey),
                      border: const OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey),
                      ),
                      focusedBorder: const OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue),
                      ),
                      contentPadding: const EdgeInsets.all(12),
                      counterText: '',
                      fillColor: Colors.grey[800],
                      filled: true,
                    ),
                    autofocus: true,
                    // 提交过程中禁用输入
                    enabled: !_isSubmitting,
                  ),
                ),

                Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    '$_currentLength/$_maxLength',
                    style: TextStyle(
                      fontSize: 12,
                      color: _currentLength >= _maxLength
                          ? Colors.red
                          : Colors.white70,
                    ),
                  ),
                ),

                const SizedBox(height: 20),

                // 提交按钮 - 提交过程中或显示空提示时禁用
                ElevatedButton(
                  onPressed: (_isSubmitting || _isShowingEmptyHint)
                      ? null
                      : _submitFeedback,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    backgroundColor: Theme.of(context).primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    // 禁用状态下的样式
                    disabledBackgroundColor: Theme.of(
                      context,
                      // ignore: deprecated_member_use
                    ).primaryColor.withOpacity(0.5),
                  ),
                  child: Text(
                    '提交反馈'.tr,
                    style: const TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ),
              ],
            ),
          ),

          if (_isLoading)
            Container(
              color: Colors.transparent,
              alignment: Alignment.center,
              child: const CircularProgressIndicator(),
            ),
        ],
      ),
    ),
  );
}
